// stores/pet.ts
import { defineStore } from 'pinia'
import { reactive, computed } from 'vue'

export type PetState = 'hidden' | 'greeting' | 'normal'

export interface Pet {
  user_id: string | number
  name: string
  hidden_gif: string
  greeting_gif: string
  normal_gif: string
  greeting: string
  position: { left: number; bottom: number }
  state: PetState
  avatar: string
}

const STORAGE_KEY = 'pet_state_v1'

const defaultPet: Pet = {
  user_id: 1,
  name: '小玖',
  hidden_gif: 'https://tc.z.wiki/autoupload/f/TyumWnX8p21CgRtTc_AMyO80_Okujp8g-GuQ63zvXsyyl5f0KlZfm6UsKj-HyTuv/20250831/BbSF/832X920/%E7%BD%97%E5%B0%8F%E9%BB%91-%E8%B6%B4%E7%9D%80-%E9%80%8F%E6%98%8E%E8%83%8C%E6%99%AF_white_bg.gif/webp',
  greeting_gif: 'https://tc-new.z.wiki/autoupload/f/TyumWnX8p21CgRtTc_AMyO80_Okujp8g-GuQ63zvXsyyl5f0KlZfm6UsKj-HyTuv/20250831/Bkzf/848X1108/%E7%BD%97%E5%B0%8F%E9%BB%91-%E7%AB%99%E7%9D%80-%E7%99%BD%E8%89%B2%E8%83%8C%E6%99%AF-%E5%8A%A8%E5%9B%BE.gif/webp',
  normal_gif: 'https://tc-new.z.wiki/autoupload/f/TyumWnX8p21CgRtTc_AMyO80_Okujp8g-GuQ63zvXsyyl5f0KlZfm6UsKj-HyTuv/20250831/tosy/782X1190/%E7%BD%97%E5%B0%8F%E9%BB%91v2_white_bgv1.gif/webp',
  greeting: '你好，我是你的宠物！',
  position: { left: 20, bottom: 50 },
  state: 'hidden',
  avatar: ''
}

function loadFromLocal(): Partial<Pet> | null {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    return raw ? JSON.parse(raw) : null
  } catch { return null }
}

function saveToLocal(pet: Pet) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(pet)) } catch {}
}

export const usePetStore = defineStore('pet', () => {
  const pet = reactive<Pet>({ ...defaultPet, ...(loadFromLocal() || {}) })

  const currentGif = computed(() => {
    if (pet.state === 'hidden')   return pet.hidden_gif
    if (pet.state === 'greeting') return pet.greeting_gif
    return pet.normal_gif
  })

  function patch(data: Partial<Pet>) {
    Object.assign(pet, data)
    saveToLocal(pet)
  }

  function setState(s: PetState) {
    pet.state = s
    saveToLocal(pet)
  }

  function setPosition(pos: { left?: number; bottom?: number }) {
    pet.position = { ...pet.position, ...pos }
    saveToLocal(pet)
  }

  return { pet, currentGif, patch, setState, setPosition }
})
